package com.rfy.framework.startup;

import org.apache.commons.lang.StringUtils;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.context.ApplicationContext;
import org.springframework.util.ClassUtils;

/**
 * @author: yadongcui
 * @date: 2019-01-19 10:51
 * @description：springboot 项目启动参数
 */
public abstract class AbstractRunApp {

    /***
     * springboot的全局配置文件路径变量名
     */
    public static String SPRING_CONFIG_PATH = "spring.com.rfy.user.config.location";

    /**
     * dpboot的全局配置文件路径变量名
     */
    public static String DPBOOT_CONFIG_PATH = "global.com.rfy.user.config.path";

    /***
     * dpboot配置文件名，不需要路径 ，但要包括扩展名
     */
    public static String DPBOOT_CONFIG_FILES = "system-com.rfy.user.config.properties";

    /**
     * dsf application startup
     * @param clazz
     * @param args
     */
    protected static void dsfStartup(Class<? extends AbstractRunApp> clazz, boolean startWeb, String[] args) {
        String configPath = System.getProperty(DPBOOT_CONFIG_PATH);
        if (StringUtils.isBlank(configPath)) {
            // jvm参数获取不到, 默认从工程根下configs目录读取
            String basePath = ClassUtils.getDefaultClassLoader().getResource("").getPath();
            configPath = StringUtils.substringBefore(basePath, "target") + "configs/";
            System.setProperty(DPBOOT_CONFIG_PATH, configPath);
        }
        if (StringUtils.isEmpty(configPath)) {
            throw new RuntimeException("you must set environment " + DPBOOT_CONFIG_PATH + " before run!");
        }

        ApplicationContext ctx = new SpringApplicationBuilder(clazz)
                .properties(SPRING_CONFIG_PATH + "=" + configPath + DPBOOT_CONFIG_FILES).web(startWeb).run(args);
    }
}
